<template>
  <PageTemplate title="短视频">
    <template #default>
      <view class="video-container">
        <!-- 视频列表 -->
        <scroll-view 
          class="scroll-container"
          scroll-y="true" 
          @scrolltolower="loadMore"
          :refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          v-if="videoList.length > 0"
        >
          <view 
            class="publish-card" 
            v-for="video in videoList" 
            :key="video.video_id"
          >
            <!-- 卡片头部（用户信息和时间） -->
            <view class="card-header">
              <view class="user-info">
                <image class="avatar" :src="video.author?.avatar || '/static/logo.png'" mode="widthFix" />
                <view class="user-meta">
                  <text class="user-name">{{ video.author?.name || '匿名用户' }}</text>
                </view>
              </view>

              <view class="publish-time">
                <image class="time-icon" src="/static/publish/i-clock.png" mode="aspectFit" />
                <text>{{ formatDate(video.createdAt) }}</text>
              </view>
            </view>
            
            <!-- 卡片内容区 -->
            <view class="card-content">
              <!-- 文字内容 -->
              <view class="content-text" v-if="video.title && video.title.trim()">
                <text>{{ video.title }}</text>
              </view>

              <!-- 视频封面 -->
              <view class="content-imgs">
                <view class="img-grid single-image">
                  <view class="video-container-wrapper">
                    <image 
                      :src="video.cover_image?.fileurl"
                      class="publish-img" 
                      mode="widthFix"
                    />
                    <view class="play-icon" @click="playVideo(video)">
                      <image class="play-icon-img" src="/static/video/i-bofang.png" mode="aspectFit"></image>
                    </view>
                  </view>
                </view>
              </view>
            </view>

            <!-- 互动区域 -->
            <view class="card-actions">
              <view class="action-item" @click="handleVideoLike(video)">
                <image
                    class="action-icon"
                    :src="video.is_liked ? '/static/video/i-dianzhan.png' : '/static/video/i-quxiaodianzan.png'"
                    mode="aspectFit" />
                <text class="action-text">{{ video.like_count }}</text>
              </view>
              <view class="action-item" @click="focusCommentInput(video)">
                <image class="action-icon" src="/static/video/i-pinglun.png" mode="aspectFit" />
                <text class="action-text">{{ video.comment_count }}</text>
              </view>
              <view class="action-item">
                <image class="action-icon" src="/static/video/i-bofangtongji.png" mode="aspectFit" />
                <text class="action-text">{{ video.play_count }}</text>
              </view>
            </view>

            <!-- 评论区域 -->
            <view class="comment-area" v-if="video.showComments || (video.comments && video.comments.length > 0)">
              <!-- 评论列表 -->
              <view class="comments-list" v-if="video.comments && video.comments.length > 0">
                <view class="comment-item" v-for="comment in video.comments" :key="comment.comment_id">
                  <image class="comment-avatar" :src="comment.author.avatar || '/static/logo.png'" mode="aspectFill" />
                  <view class="comment-content">
                    <view class="comment-user">{{ comment.author.name }}</view>
                    <view class="comment-text">{{ comment.content }}</view>
                    <view class="comment-meta">
                      <text class="comment-time">{{ formatDate(comment.createdAt) }}</text>
                    </view>
                  </view>
                </view>
              </view>
              <!-- 无评论提示 -->
              <view class="no-comments" v-else>
                <text>暂无评论，快来抢沙发吧~</text>
              </view>

              <!-- 评论输入框 -->
              <view class="comment-input-container">
                <textarea
                    class="comment-input"
                    placeholder="写评论..."
                    v-model="video.new_comment"
                    :auto-height="true"
                    @confirm="handleVideoCommentSubmit(video)"
                />
                <button class="send-button" @click="handleVideoCommentSubmit(video)">发送</button>
              </view>
            </view>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="loading-more" v-if="loadingMore">
            <image class="loading-icon" src="/static/publish/i-jiazaizhong.png" mode="aspectFit" />
          </view>
          
          <!-- 到底了提示 -->
          <view class="no-more" v-else-if="noMore && videoList.length > 0">
            <image class="no-more-icon" src="/static/publish/i-daodile.png" mode="aspectFit" />
          </view>
        </scroll-view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="videoList.length === 0 && !loading && !refreshing">
          <image class="empty-icon" src="/static/publish/i-meiyoushuju.png" mode="aspectFit" />
          <text class="empty-text">暂无视频</text>
        </view>
        
        <!-- 视频播放模态框 -->
        <VideoModal 
          v-if="currentVideo" 
          :video="currentVideo" 
          @close="closeVideoModal"
          @like="handleVideoLikeFromModal"
          @comment="handleVideoComment"
        />
      </view>
    </template>
  </PageTemplate>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { getShortVideoList, getShortVideoById, playShortVideo, getShortVideoCommentList, likeShortVideo, unlikeShortVideo, createShortVideoComment } from '@/api/video/index.ts'
import { showToast, formatDate } from '@/utils/index.ts'
import PageTemplate from '@/components/PageTemplate.vue';
import VideoModal from './VideoModal.vue';

// 视频列表相关
const videoList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const currentPage = ref(1)
const pageSize = ref(10) // 参考home.vue的实现
const totalPages = ref(0)
const currentVideo = ref(null)
const refreshing = ref(false) // 下拉刷新状态
const noMore = ref(false) // 是否还有更多数据
const isLoading = ref(false) // 防重复加载标志

// 聚焦评论输入框
const focusCommentInput = (video) => {
  // 切换评论区域显示状态
  video.showComments = !video.showComments;
}

// 发表评论
const handleVideoCommentSubmit = async (video) => {
  if (!video.new_comment || video.new_comment.trim() === '') {
    showToast('请输入评论内容')
    return
  }

  try {
    const res = await createShortVideoComment({
      video_id: video.video_id,
      content: video.new_comment
    })

    // 初始化评论数组
    if (!video.comments) {
      video.comments = []
    }

    // 添加新评论到开头
    video.comments.unshift(res.data)
    video.comment_count++
    video.new_comment = '' // 清空输入框

    showToast('评论成功', 'success')
  } catch (err) {
    console.error('评论失败:', err)
  }
}

// 处理视频点赞事件（从列表中）
const handleVideoLike = async (video) => {
  try {
    let res;
    if (video.is_liked) {
      // 取消点赞
      res = await unlikeShortVideo({ video_id: video.video_id })
      if (res.code === 200) {
        video.is_liked = false
        video.like_count--
        showToast('已取消点赞')
      }
    } else {
      // 点赞
      res = await likeShortVideo({ video_id: video.video_id })
      if (res.code === 200) {
        video.is_liked = true
        video.like_count++
        showToast('点赞成功')
      }
    }
  } catch (err) {
    console.error('操作失败:', err)
  }
}

// 处理视频点赞事件（从模态框中）
const handleVideoLikeFromModal = ({ liked, count }) => {
  if (currentVideo.value) {
    currentVideo.value.is_liked = liked
    currentVideo.value.like_count = count
    
    // 更新列表中的点赞状态和数量
    const index = videoList.value.findIndex(v => v.video_id === currentVideo.value.video_id)
    if (index !== -1) {
      videoList.value[index].is_liked = liked
      videoList.value[index].like_count = count
    }
  }
}

// 处理视频评论事件
const handleVideoComment = (newComment) => {
  if (currentVideo.value) {
    // 初始化评论数组
    if (!currentVideo.value.comments) {
      currentVideo.value.comments = []
    }
    
    // 添加新评论到列表开头
    currentVideo.value.comments.unshift(newComment)
    currentVideo.value.comment_count++
    
    // 更新列表中的评论数量
    const index = videoList.value.findIndex(v => v.video_id === currentVideo.value.video_id)
    if (index !== -1) {
      videoList.value[index].comment_count = currentVideo.value.comment_count
    }
  }
}

// 获取视频评论列表
const fetchComments = async () => {
  try {
    const res = await getShortVideoCommentList({
      video_id: currentVideo.value.video_id,
      page: 1,
      limit: 20
    })
    
    if (res.code === 200) {
      currentVideo.value.comments = res.data.list
    }
  } catch (err) {
    console.error('获取评论失败:', err)
    showToast('获取评论失败')
  }
}

// 获取视频列表
const fetchVideoList = async (page = 1) => {
  // 防止重复加载
  if (isLoading.value && page > 1) return
  
  // 设置加载状态
  isLoading.value = true
  if (page === 1 && !refreshing.value) {
    loading.value = true
  } else if(page === 1 && refreshing.value) {
    // 下拉刷新时不显示加载状态
  } else {
    loadingMore.value = true
  }
  
  try {
    const res = await getShortVideoList({
      page,
      limit: pageSize.value
    })
    
    if (res.code === 200) {
      const newVideos = res.data.list
      
      // 处理数据，添加评论和点赞状态字段
      newVideos.forEach(video => {
        video.new_comment = ''
        // 从服务器返回的数据中获取实际的点赞状态
        video.is_liked = video.is_liked || false
        video.showComments = false // 默认不显示评论区域
        // 直接使用后端返回的评论数据
        video.comments = video.comments || []
      })
      
      if (page === 1) {
        videoList.value = newVideos
        // 判断是否还有更多数据
        if (newVideos.length < pageSize.value) {
          noMore.value = true
        } else {
          noMore.value = false // 重置，允许继续加载
        }
      } else {
        videoList.value = [...videoList.value, ...newVideos]
        // 判断是否还有更多数据
        if (newVideos.length < pageSize.value) {
          noMore.value = true
        }
      }
      
      currentPage.value = page
      totalPages.value = res.data.pagination.total_pages
    }
  } catch (error) {
    console.error('获取视频列表失败:', error)
  } finally {
    // 重置加载状态
    isLoading.value = false
    loading.value = false
    loadingMore.value = false
    refreshing.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!loading.value && !noMore.value && !isLoading.value) {
    fetchVideoList(currentPage.value + 1)
  }
}

// 下拉刷新
const onRefresh = async () => {
  if (refreshing.value) return
  refreshing.value = true
  currentPage.value = 1
  noMore.value = false
  await fetchVideoList(1)
}

// 播放视频
const playVideo = async (video) => {
  try {
    // 先获取视频详情
    const res = await getShortVideoById({
      video_id: video.video_id
    })
    
    if (res.code === 200) {
      currentVideo.value = res.data
      
      // 添加点赞和评论相关字段
      currentVideo.value.is_liked = currentVideo.value.is_liked || false
      currentVideo.value.comments = []
      
      // 获取评论列表
      await fetchComments()
      
      // 增加播放次数
      await playShortVideo({
        video_id: video.video_id
      })
      
      // 更新播放次数
      currentVideo.value.play_count += 1
      
      // 更新列表中的播放次数
      const index = videoList.value.findIndex(v => v.video_id === video.video_id)
      if (index !== -1) {
        videoList.value[index].play_count = currentVideo.value.play_count
      }
      
      // 在下一个tick中尝试自动播放
      nextTick(() => {
        // 微信小程序中需要在用户交互后手动播放
        //#ifdef MP-WEIXIN
        const videoContext = uni.createVideoContext('videoPlayer')
        videoContext.play()
        //#endif
      })
    }
  } catch (error) {
    console.error('播放视频失败:', error)
    let errorMsg = '播放视频失败'
    if (error.errMsg && error.errMsg.includes('https')) {
      errorMsg = '视频播放失败，可能是SSL证书问题'
    }
  }
}

// 关闭视频模态框
const closeVideoModal = () => {
  //#ifdef MP-WEIXIN
  // 退出全屏
  const videoContext = uni.createVideoContext('videoPlayer')
  videoContext.exitFullScreen()
  //#endif
  currentVideo.value = null
}

// 初始化
onMounted(() => {
  fetchVideoList()
})
</script>

<style scoped lang="scss">
.video-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  overflow: auto;
  padding: 0 30rpx;
  height: 100%;
}

.publish-card {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.publish-time {
  font-size: 24rpx;
  color: #999;
  display: flex;
  align-items: center;
}

.time-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 8rpx;
}

.card-content {
  margin-bottom: 20rpx;
}

.content-text {
  font-size: 30rpx;
  line-height: 1.5;
  color: #333;
  margin-bottom: 20rpx;
}

.content-imgs {
  margin-bottom: 20rpx;
}

.img-grid {
  display: grid;
  grid-gap: 10rpx;
}

.single-image {
  width: 100%;
  max-width: 400rpx;
}

.single-image .publish-img {
  width: 100%;
  border-radius: 10rpx;
}

.video-container-wrapper {
  position: relative;
  width: 100%;
  height: 420rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
  border-radius: 10rpx;
  overflow: hidden;
}

.video-container-wrapper .publish-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.play-icon-img {
  width: 50rpx;
  height: 50rpx;
}

.card-actions {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.action-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
}

.action-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 10rpx;
}

.action-text {
  font-size: 28rpx;
  color: #666666;
}

.comment-area {
  background-color: #f8f9fa;
  border-radius: 10rpx;
  padding: 20rpx;
}

.comment-input-container {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 10rpx;
  padding: 6rpx;
  background-color: #ffffff;
  border-radius: 36rpx;
  border: 1rpx solid #f0f0f0;
  min-height: 70rpx;
}

.comment-input {
  flex: 1;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: transparent;
  border: none;
  outline: none;
  min-height: 50rpx;
  line-height: 40rpx;
  vertical-align: middle;
  resize: none;
  width: 100%;
}

.send-button {
  font-size: 26rpx;
  padding: 12rpx 24rpx;
  background: linear-gradient(90deg, #ff7e5f, #feb47b);
  color: white;
  border-radius: 30rpx;
  border: none;
  box-shadow: 0 4rpx 10rpx rgba(255, 126, 95, 0.3);
  height: auto;
  line-height: normal;
}

.comments-list {
  max-height: none;
  overflow-y: visible;
}

.comment-item {
  display: flex;
  margin-bottom: 20rpx;
  padding: 10rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
}

.comment-avatar {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  margin-right: 15rpx;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-weight: bold;
  font-size: 26rpx;
  margin-bottom: 5rpx;
  color: #333;
}

.comment-text {
  font-size: 28rpx;
  line-height: 1.4;
  margin-bottom: 5rpx;
  color: #666;
}

.comment-meta {
  display: flex;
  font-size: 24rpx;
  color: #999999;
}

.no-comments {
  text-align: center;
  padding: 30rpx;
  font-size: 26rpx;
  color: #999;
}

.loading-more {
  text-align: center;
  padding: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-icon {
  width: 120rpx;
  height: 120rpx;
}

.no-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  color: #999;
}

.no-more-icon {
  width: 220rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 32rpx;
}

.empty-icon {
  width: 220rpx;
  height: 220rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.video-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.video-modal-content {
  width: 90%;
  max-width: 700px;
  background: #000;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
}

.video-player {
  width: 100%;
  height: 420rpx;
  background-color: #000;
}
</style>